﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Data.Odbc;
using System.Data;
using System.Xml.Serialization;
using WLMCoreLibrary;
using System.Configuration;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
//using ASPJPEGLib;
using System.Web;


namespace MiWebSite_Core
{
	[XmlType("Image")]
	public class MiWebSiteMediaImages : BaseClass
	{
		

		#region public properties
		[XmlAttribute()]
		public String titulo {get;set; }
		[XmlAttribute()]
		public String descripcion {get;set; }
		[XmlAttribute()]
		public String archivo {get;set; }
		[XmlAttribute()]
		public int tamano {get;set; }
		[XmlAttribute()]
		public int idCategoria {get;set; }
		[XmlAttribute()]
		public int aspecto {get;set; }
		[XmlAttribute()]
		public string URLImagen
		{
			get
			{
				WebSiteMainConfiguration config= WebSiteMainConfiguration.GetConfig();
				if (id != 0)
					return config.Settings["imagePath"].value + fechaCreacion.Year + "/" + fechaCreacion.Month + "/" + fechaCreacion.Day + "/" + archivo;
				else
					return config.Settings["imagePath"].value + "/imagenError.jpg";
			}
			set { archivo = value; }
		}
		[XmlAttribute()]
		public string FullURL
		{
			get
			{
				return "http://" + CurrentDomain.SubDomain + "." + CurrentDomain.DomainName + URLImagen;
			}
			
		}
		#endregion

		#region constructors
		public MiWebSiteMediaImages()
		{
		}

		public MiWebSiteMediaImages(ref dbConnector ConexionDB)
		{
			ConexionDBInterna = ConexionDB;
			WLMClassBinder classBinder = new WLMClassBinder(ref ConexionDB);
		id = classBinder.NewRecord("imagenes");
			string queryString = "";
			queryString = "SELECT * FROM imagenes WHERE id=\"" + id + "\"";
			GetRecord(queryString);
		}

		public MiWebSiteMediaImages(int registryId, ref dbConnector ConexionDB)
		{
			ConexionDBInterna = ConexionDB;
			string queryString = "";
			queryString = "SELECT * FROM imagenes WHERE id='" + registryId + "'";
			WLMClassBinder classBinder = new WLMClassBinder(ref ConexionDB);
			GetRecord(queryString);
		}


		public string UploadImage()
		{
			WebSiteMainConfiguration config = WebSiteMainConfiguration.GetConfig();
			string nombreArchivo = config.Settings["nombreAplicacion"].value + this.id + ".jpg";
			// tamano=WLMFunctions.UploadImage(this.id);
			archivo = nombreArchivo;
			if (tamano > 0)
				this.Save();
			else
			{
				this.Delete();
				return "";
			}

			return nombreArchivo;
		}
		#endregion

		#region public methods

		public int OptimizarImagen(Stream streamFile)
		{
			WebSiteMainConfiguration config = WebSiteMainConfiguration.GetConfig();
			DateTime fecha = fechaCreacion;
			return ResizeImage(streamFile, archivo, config.Settings["imagePath"].value + fecha.Year + "/" + fecha.Month + "/" + fecha.Day + "/", Convert.ToInt32(config.Settings["imageWidth"].value));

		}


		private bool cosas()
		{
			return false;
		}





		public void Delete()
		{
			string queryString = "";
			queryString = "DELETE FROM imagenes WHERE id=\"" + id + "\"";
			ConexionDBInterna.ExecuteCommand(queryString);

		}
		#endregion


		#region Private Methods
		private ImageCodecInfo GetEncoder(ImageFormat format)
		{

			ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

			foreach (ImageCodecInfo codec in codecs)
			{
				if (codec.FormatID == format.Guid)
				{
					return codec;
				}
			}
			return null;
		}

		public string GetThumbNail(int thumbSize)
		{
			try
			{
				WebSiteMainConfiguration config = WebSiteMainConfiguration.GetConfig();
				string path1 = config.Settings["sitePath"].value;
				string nuevoNombreArchivo = archivo.Split('.')[0] + "_" + thumbSize.ToString() + "." + archivo.Split('.')[1];
				if (!File.Exists(path1 + config.Settings["thumbsPath"].value + nuevoNombreArchivo))
				{
					FileStream lecto = new FileStream(path1 + config.Settings["imagePath"].value + fechaCreacion.Year + "/" + fechaCreacion.Month + "/" + fechaCreacion.Day + "/" + archivo, FileMode.Open);

					ResizeImage(lecto, nuevoNombreArchivo, config.Settings["thumbsPath"].value, thumbSize);
					lecto.Close();

				}
				return config.Settings["thumbsPath"].value + nuevoNombreArchivo;
			}
			catch { return ""; }

		}

		private int ResizeImage(Stream streamFile, string fileName, string directoryName, int imageWidthResize)
		{
			WebSiteMainConfiguration config = WebSiteMainConfiguration.GetConfig();
			string path1 = config.Settings["sitePath"].value;

			//Bitmap bmp1 = new Bitmap(ConfigurationManager.AppSettings["sitePath"] + ConfigurationManager.AppSettings["imagesPath"] + _archivo);
			Bitmap bmp1 = new Bitmap(streamFile);

			//Or you do can use buil-in method
			//ImageCodecInfo jgpEncoder GetEncoderInfo("image/gif");//"image/jpeg",...
			ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);

			// Create an Encoder object based on the GUID
			// for the Quality parameter category.
			System.Drawing.Imaging.Encoder myEncoder =
			System.Drawing.Imaging.Encoder.Quality;

			// Create an EncoderParameters object.
			// An EncoderParameters object has an array of EncoderParameter
			// objects. In this case, there is only one
			// EncoderParameter object in the array.
			EncoderParameters myEncoderParameters = new EncoderParameters(1);

			EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 78L);
			myEncoderParameters.Param[0] = myEncoderParameter;



			System.IO.DirectoryInfo directorio = new System.IO.DirectoryInfo(path1 + directoryName);
			if (!directorio.Exists)
				directorio.Create();
			string finalFileName=config.Settings["sitePath"].value + directoryName + fileName;
			if (bmp1.Width > imageWidthResize)
			{
				if (fileName.Split('.')[fileName.Split('.').Length - 1] == "gif")
				{
					jgpEncoder = GetEncoder(ImageFormat.Gif);
				}
				if (fileName.Split('.')[fileName.Split('.').Length - 1] == "png")
				{
					jgpEncoder = GetEncoder(ImageFormat.Png);
				}
				int srcWidth = bmp1.Width;
				int srcHeight = bmp1.Height;

				Decimal sizeRatio = ((Decimal)srcHeight / srcWidth);
				int thumbHeight = Decimal.ToInt32(sizeRatio * imageWidthResize);

				Bitmap bmp = new Bitmap(imageWidthResize, thumbHeight);

				System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);

				gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
				gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
				gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
				System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, imageWidthResize, thumbHeight);
				gr.DrawImage(bmp1, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
				bmp.Save(finalFileName, jgpEncoder, myEncoderParameters);

			}
			else
			{
				bmp1.Save(finalFileName, jgpEncoder, myEncoderParameters);
			}
			bmp1.Dispose();
			FileInfo info= new FileInfo(finalFileName);
			return Convert.ToInt32(info.Length);

			//File.Delete(ConfigurationManager.AppSettings["sitePath"] + ConfigurationManager.AppSettings["imagesPath"] + _archivo);
			//_archivo = nuevoId0.ToString() + "." + extencion;
			//_tamano = (int)new FileInfo(ConfigurationManager.AppSettings["sitePath"] + directoryName + archivo).Length;

		}


		private void GetRecord(string queryString)
		{
			OdbcDataReader reader = ConexionDBInterna.ExecuteReader(queryString);
			if (reader.HasRows)
			{
				if (!reader.IsDBNull(reader.GetOrdinal("id")))
				id = (System.Int32)reader["id"];
				if (!reader.IsDBNull(reader.GetOrdinal("fechaCreacion")))
				fechaCreacion = Convert.ToDateTime(reader["fechaCreacion"]); if (!reader.IsDBNull(reader.GetOrdinal("fechaModificacion"))) fechaModificacion = Convert.ToDateTime(reader["fechaModificacion"]); if (!reader.IsDBNull(reader.GetOrdinal("idUsuarioModificacion"))) idUsuarioModificacion = (System.Int32)reader["idUsuarioModificacion"];


				if (!reader.IsDBNull(reader.GetOrdinal("titulo")))
				titulo = (System.String)reader["titulo"];
				if (!reader.IsDBNull(reader.GetOrdinal("descripcion")))
				descripcion = (System.String)reader["descripcion"];
				if (!reader.IsDBNull(reader.GetOrdinal("archivo")))
				archivo = (System.String)reader["archivo"];
				if (!reader.IsDBNull(reader.GetOrdinal("tamano")))
				tamano = (System.Int32)reader["tamano"];
				if (!reader.IsDBNull(reader.GetOrdinal("idCategoria")))
				idCategoria = (System.Int32)reader["idCategoria"];
				if (!reader.IsDBNull(reader.GetOrdinal("idUsuario")))
				idUsuario = (System.Int32)reader["idUsuario"];
				if (!reader.IsDBNull(reader.GetOrdinal("aspecto")))
				aspecto = (System.Int32)reader["aspecto"];
			}
		}


		protected override void UpdateBind()
		{
			StringBuilder strCommand = new StringBuilder();
			strCommand.Append("UPDATE imagenes set "); strCommand.Append("fechaModificacion='" + this.fechaModificacion.ToString("yyyy-MM-dd HH:mm:ss") + "'"); strCommand.Append(",idUsuarioModificacion=\"" + idUsuarioModificacion.ToString() + "\"");
			strCommand.Append(",titulo=\"" + titulo + "\"");
			strCommand.Append(",descripcion=\"" + descripcion + "\"");
			strCommand.Append(",archivo=\"" + archivo + "\"");
			strCommand.Append(",tamano=\"" + tamano.ToString() + "\"");
			strCommand.Append(",idCategoria=\"" + idCategoria.ToString() + "\"");
			strCommand.Append(",aspecto=\"" + aspecto.ToString() + "\"");
			strCommand.Append(" WHERE id=\"" + id + "\"");
			ConexionDBInterna.ExecuteCommand(strCommand.ToString());
		}
		#endregion

	}

	public class MiWebSiteMediaImagesCollection
	{

        public List<MiWebSiteMediaImages> Elementos { get; set; }

        public MiWebSiteMediaImagesCollection()
        {
        }

		public MiWebSiteMediaImagesCollection(ref dbConnector ConexionDB)
		{
			string strCommand = "SELECT id FROM IMAGENES order by id desc";
			OdbcDataReader reader = ConexionDB.ExecuteReader(strCommand);
		Elementos = new List<MiWebSiteMediaImages>();
			while (reader.Read())
			{
				MiWebSiteMediaImages newEntry = new MiWebSiteMediaImages(Convert.ToInt32(reader["id"]), ref ConexionDB);


			Elementos.Add(newEntry);
			}
			reader.Close();
			reader.Dispose();
		}

		public MiWebSiteMediaImagesCollection(int idGaleria, ref dbConnector ConexionDB)
		{
			string strCommand = "SELECT id FROM IMAGENES WHERE idCategoria='" + idGaleria + "' order by id DESC";

			OdbcDataReader reader = ConexionDB.ExecuteReader(strCommand);
		Elementos = new List<MiWebSiteMediaImages>();
			while (reader.Read())
			{
				MiWebSiteMediaImages newEntry = new MiWebSiteMediaImages(Convert.ToInt32(reader["id"]), ref ConexionDB);


			Elementos.Add(newEntry);
			}
			reader.Close();
			reader.Dispose();
		}

		public MiWebSiteMediaImagesCollection(int idGaleria, bool sip, ref dbConnector ConexionDB)
		{
			string strCommand = "SELECT id FROM IMAGENES WHERE idCategoria='" + idGaleria + "' order by aspecto ASC";

			OdbcDataReader reader = ConexionDB.ExecuteReader(strCommand);
		Elementos = new List<MiWebSiteMediaImages>();
			while (reader.Read())
			{
				MiWebSiteMediaImages newEntry = new MiWebSiteMediaImages(Convert.ToInt32(reader["id"]), ref ConexionDB);


			Elementos.Add(newEntry);
			}
			reader.Close();
			reader.Dispose();
		}
	}


	public class Galeria : BaseClass
	{
		

		#region public properties
		public String nombre {get;set; }
		public String galName {get;set; }
		public String descripcion {get;set; }
		public int noFotos {get;set; }
		public Boolean publica {get;set; }
		#endregion

		#region constructors
		public Galeria()
		{
		}

		public Galeria(ref dbConnector ConexionDB)
		{
			ConexionDBInterna = ConexionDB;
			WLMClassBinder classBinder = new WLMClassBinder(ref ConexionDB);
		id = classBinder.NewRecord("GALERIAS");
			string queryString = "";
			queryString = "SELECT * FROM GALERIAS WHERE id='" + id + "'";
			GetRecord(queryString);
		}

		public Galeria(int registryId, ref dbConnector ConexionDB)
		{
			ConexionDBInterna = ConexionDB;
			string queryString = "";
			queryString = "SELECT * FROM GALERIAS WHERE id='" + registryId + "'";
			this.GetRecord(queryString);
		}
		public Galeria(DataRow dataRow, ref dbConnector ConexionDB)
		{

			this.GetRecord(dataRow);
		}
		#endregion

		#region public methods
		public void Delete()
		{
			string queryString = "";
			queryString = "DELETE FROM GALERIAS WHERE id='" + id + "'";
			ConexionDBInterna.ExecuteCommand(queryString);
		}
		#endregion

		#region Private Methods
		private void GetRecord(string queryString)
		{
			OdbcDataReader reader = ConexionDBInterna.ExecuteReader(queryString);
			if (reader.HasRows)
			{
				if (!reader.IsDBNull(reader.GetOrdinal("id")))
				id = (System.Int32)reader["id"];
				if (!reader.IsDBNull(reader.GetOrdinal("fechaCreacion")))
				fechaCreacion = Convert.ToDateTime(reader["fechaCreacion"]);
				if (!reader.IsDBNull(reader.GetOrdinal("fechaModificacion")))
				fechaModificacion = Convert.ToDateTime(reader["fechaModificacion"]);
				if (!reader.IsDBNull(reader.GetOrdinal("idUsuario")))
				idUsuario = (System.Int32)reader["idUsuario"];
				if (!reader.IsDBNull(reader.GetOrdinal("idUsuarioModificacion")))
				idUsuarioModificacion = (System.Int32)reader["idUsuarioModificacion"];
				if (!reader.IsDBNull(reader.GetOrdinal("nombre")))
				nombre = (System.String)reader["nombre"];
				if (!reader.IsDBNull(reader.GetOrdinal("galName")))
				galName = (System.String)reader["galName"];
				if (!reader.IsDBNull(reader.GetOrdinal("descripcion")))
				descripcion = (System.String)reader["descripcion"];
				if (!reader.IsDBNull(reader.GetOrdinal("noFotos")))
				noFotos = (System.Int32)reader["noFotos"];
				if (!reader.IsDBNull(reader.GetOrdinal("publica")))
				publica = Convert.ToBoolean(reader["publica"]);
			}
		}


		private void GetRecord(DataRow dataRow)
		{
			if (dataRow != null)
			{
				if (dataRow["id"] != null)
				id = (System.Int32)dataRow["id"];
				if (dataRow["fechaCreacion"] != null)
				fechaCreacion = (System.DateTime)dataRow["fechaCreacion"];
				if (dataRow["fechaModificacion"] != null)
				fechaModificacion = (System.DateTime)dataRow["fechaModificacion"];
				if (dataRow["idUsuario"] != null)
				idUsuario = (System.Int32)dataRow["idUsuario"];
				if (dataRow["idUsuarioModificacion"] != null)
				idUsuarioModificacion = (System.Int32)dataRow["idUsuarioModificacion"];
				if (dataRow["nombre"] != null)
				nombre = (System.String)dataRow["nombre"];
				if (dataRow["galName"] != null)
				galName = (System.String)dataRow["galName"];
				if (dataRow["descripcion"] != null)
				descripcion = (System.String)dataRow["descripcion"];
				if (dataRow["noFotos"] != null)
				noFotos = (System.Int32)dataRow["noFotos"];
				if (dataRow["publica"] != null)
				publica = (bool)dataRow["publica"];
			}
		}


		protected override void UpdateBind()
		{
			StringBuilder strCommand=new StringBuilder();
			strCommand.Append("UPDATE GALERIAS set ");
			strCommand.Append("fechaModificacion='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'");
			strCommand.Append(",idUsuarioModificacion='" + idUsuarioModificacion.ToString() + "'");
			strCommand.Append(",nombre=\"" + WLMFunctions.comillas(nombre) + "\"");
			strCommand.Append(",galName=\"" + WLMFunctions.comillas(galName) + "\"");
			strCommand.Append(",descripcion=\"" + WLMFunctions.comillas(descripcion) + "\"");
			strCommand.Append(",noFotos='" + noFotos.ToString() + "'");
			strCommand.Append(",publica='" + Convert.ToInt16(publica) + "'");
			strCommand.Append(" WHERE id='" + id + "'");
			ConexionDBInterna.ExecuteCommand(strCommand.ToString());
		}
		#endregion
	}




	public class GaleriasCollection
	{
		private dbConnector ConexionDB;
        public BaseClassArray<Galeria> Elementos { get; set; }
		public GaleriasCollection()
		{
		}
		public GaleriasCollection(ref dbConnector dbConn)
		{

			string strCommand = "SELECT id FROM GALERIAS ";
			OdbcDataReader dataReader = ConexionDB.ExecuteReader(strCommand);
		Elementos = new BaseClassArray<Galeria>();
			while (dataReader.Read())
			{
				Galeria newItem = new Galeria(Convert.ToInt32(dataReader["id"]), ref ConexionDB);
			Elementos.Add(newItem);
			}
			dataReader.Close();
			dataReader.Dispose();
		}
	}
}
